package com.dhecp.framework.shiro.service;

import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.dhecp.common.constant.Constants;
import com.dhecp.common.constant.ShiroConstants;
import com.dhecp.common.exception.user.UserPasswordNotMatchException;
import com.dhecp.common.exception.user.UserPasswordRetryLimitExceedException;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.security.RsaUtils;
import com.dhecp.framework.manager.AsyncManager;
import com.dhecp.framework.manager.factory.AsyncFactory;
import com.dhecp.project.system.domain.SysUserInfo;

/**
 * 密码身份验证
 */
@Component
public class SysPasswordService
{
    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;

    @PostConstruct
    public void init()
    {
        loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
    }

    /**
     * 验证登录密码是否正确
     * @param user 当前验证用户实例
     * @param password 当前验证密码
     * @author DH-Xxj
     */
    public void validate(SysUserInfo user, String password, boolean freePwd)
    {
        String loginName = user.getUserId();

        AtomicInteger retryCount = loginRecordCache.get(loginName);

        if (retryCount == null)
        {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue())
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount)));
            throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue());
        }

        if (freePwd == false) {//不免密，按原来的密码加密验证
            if (!matches(user, password)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount)));
                loginRecordCache.put(loginName, retryCount);
                throw new UserPasswordNotMatchException();
            } else {
                clearLoginRecordCache(loginName);
            }
        }else{
            if (!matchesFree(user, password)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount)));
                loginRecordCache.put(loginName, retryCount);
                throw new UserPasswordNotMatchException();
            } else {
                clearLoginRecordCache(loginName);
            }
        }
    }

    /**
     * 验证登录密码
     * @param user 当前验证用户实例
     * @param newPassword 当前验证密码
     * @return boolean
     * @author DH-Xxj
     */
    public boolean matches(SysUserInfo user, String newPassword)
    {
        return user.getUserPassWord().equals(encryptPassword(user.getUserId(), newPassword, Constants.PASSWORD_SALT));
    }


    /**
     * 免密验证数据库中加密密码
     * @param user 当前验证用户实例
     * @param newPassword 当前验证密码
     * @return boolean
     * @author DH-Xxj
     */
    public boolean matchesFree(SysUserInfo user, String newPassword)
    {
        return user.getUserPassWord().equals(newPassword);
    }

    /**
     * 验证二级密码
     * @param user 当前验证用户实例
     * @param newPassword 当前验证密码
     * @return boolean
     * @author DH-Xxj
     */
    public boolean matches2(SysUserInfo user, String newPassword)
    {
        return user.getUserPassWord2().equals(encryptPassword(user.getUserId(), newPassword, Constants.PASSWORD_SALT));
    }

    public void clearLoginRecordCache(String username)
    {
        loginRecordCache.remove(username);
    }

    public String encryptPassword(String username, String password, String salt)
    {
        return new Md5Hash(username + password + salt).toHex().toString();
    }

    public void unlock(String loginName){
        loginRecordCache.remove(loginName);
    }

    public static void main(String[] args) throws Exception
    {
        System.out.println(new SysPasswordService().encryptPassword("0000", "123456", Constants.PASSWORD_SALT));
        System.out.println(RsaUtils.encryptByPrivateKey(RsaUtils.privateKey, "123456"));
        //System.out.println(new SysPasswordService().encryptPassword("ry", "admin123", "222222"));
    }
}
